<?php

namespace plugin\kb_blog\process;

use Exception;
use Webman\App;
use plugin\kb_blog\common\View;
use plugin\kb_blog\app\model\Option;

class KbBlog extends App
{
    public function __construct()
    {
        self::$publicPath = base_path(
            DIRECTORY_SEPARATOR .
                "plugin" .
                DIRECTORY_SEPARATOR .
                "kb_blog" .
                DIRECTORY_SEPARATOR .
                "public" .
                DIRECTORY_SEPARATOR .
                "blog"
        );
    }

    /**
     * OnMessage.
     * @param TcpConnection|mixed $connection
     * @param Request|mixed $request
     * @return null
     */
    public function onMessage($connection, $request)
    {
        $path = $request->path();

        static $handler;
        if (null === $handler) {
            $handler = config('view.handler');
        }

        if (preg_match('/%[0-9a-f]{2}/i', $path)) {
            $path = urldecode($path);
            if (static::unsafeUri($connection, $path, $request)) {
                return null;
            }
        }
        if (trim($path) === "/") {
            $path = "/index.html";
        }
        try {
            $file = file_get_contents(self::$publicPath . $path);
            $file_mime = self::file_mime(self::$publicPath . $path);
            if ($file_mime === "text/html") {
                $vars = [];
                $Option = Option::all();
                if (count($Option->toArray()) > 0) {
                    foreach ($Option as $k => $v) {
                        $vars[$v["name"]] = $v["value"];
                    }
                } else {
                    $vars = [
                        'title' => '快乐两小时',
                        'keyword' => '',
                        'description' => '🌿 放 弃 总 是 很 容 易 但 坚 持 是 痛 苦 的',
                        'qrcode' => '/app/kb_blog/blog/images/qr_code.jpg',
                        'api' => 'http://127.0.0.1:8787',
                        'icp' => '粤ICP备XXXXXXXXXX号',
                        'min_title' => 'KingBes',
                        'github' => '',
                        'gitee' => '',
                        'qq' => '1234567890',
                        'wechat' => 'wechat',
                    ];
                }
                $response = response(
                    body: View::render(self::$publicPath . $path, $vars),
                    headers: ['Content-Type' => $file_mime . ";charset=utf-8"]
                );
            } else {
                $response = response(
                    body: $file,
                    headers: ['Content-Type' => $file_mime . ";charset=utf-8"]
                );
            }
        } catch (Exception $e) {
            $response = not_found();
        }

        self::send($connection, $response, $request);
        return null;
    }

    /**
     * 文件mime类型 function
     *
     * @param string $file
     * @return string
     */
    protected static function file_mime(string $file): string
    {
        $pathInfo = pathinfo($file)['extension'];
        switch ($pathInfo) {
            case "js":
                $mime_type = "text/javascript";
                break;
            case "css":
                $mime_type = "text/css";
                break;
            case "html":
                $mime_type = "text/html";
                break;
            default:
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime_type = finfo_file($finfo, $file);
                finfo_close($finfo);
        }
        return $mime_type;
    }
}
